package com.eascs.web.o2o.sd.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.axis.client.Call;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.web.o2o.sd.dao.CustomerSdDao;
import com.eascs.web.o2o.sd.entity.CustomerSd;
import com.eascs.web.o2o.sd.entity.EadbCustomer;

@Service
public class CustomerSdService {
	protected final Logger	logger	= LoggerFactory.getLogger(getClass());
	@Autowired
	private CustomerSdDao customerSdDao;
	@Value("${sd.url}")
	private String sdUrl;

	/**
	 * 插入SD数据
	 * @param customerSd
	 */
	public void saveCustomerSd(CustomerSd customerSd) {
		customerSdDao.saveEntity(customerSd);
	}

	/**
	 * 查询客户信息
	 * 
	 * @return
	 */
	public List<EadbCustomer> queryCustomerSd() {
		String sql = "select * from eaba_customer t where t.flag='N' ";
		return customerSdDao.findEntitysForMysql(sql, EadbCustomer.class);
	}
	/**
	 * 更新SD数据
	 * @param customerSd
	 */
	public void updateCustomerSd(String cno) {
		String sql = "update eaba_customer t set t.flag='Y' where t.cno=?";
		customerSdDao.excuteSql(sql, cno);
	}
	/**
	 * 同步SD数据
	 */
	public void queryCustomer(){
		String sql = "select * from eaba_customer t where t.flag='N' ";
		int pageIndex = 0;
		int pageSize = 100;
		while (pageIndex >= 0) {
			try {
				logger.info("SD同步任务,正在查询第[{}]页数据", pageIndex);
				SqlPageQuery<EadbCustomer> sqlPageQuery = new SqlPageQuery<>(EadbCustomer.class, pageSize, pageIndex, sql);
				PageResult<EadbCustomer> results = customerSdDao.findDataWithPageForMysql(sqlPageQuery);
				List<EadbCustomer> eadbList = results.getData();
				for (EadbCustomer eadbCustomer : eadbList) {
					List<CustomerSd> sdList=this.getSdInfo(eadbCustomer.getCcode(), eadbCustomer.getCno());
					if(sdList!=null && !sdList.isEmpty()){
						for (CustomerSd customerSd : sdList) {
							this.saveCustomerSd(customerSd);
							updateCustomerSd(customerSd.getCno());
						}
					}
				}
				pageIndex++;
				if (results.getPageTotal() <= pageIndex) {
					pageIndex = -1;
				}
			} catch (Exception e) {
				logger.info("入库异常:[{}]", e);
			}
			
		}
	}
	/**
	 * 调用webService接口
	 * @return
	 */
	public List<CustomerSd> getSdInfo(String customerSd,String cno){
		List<CustomerSd> sdList=new ArrayList<>();
		Date requestDate=new Date();
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM");
		String data = "<requestxml><customerCode>" + customerSd + "</customerCode><cno>" + cno + "</cno><beginDate>" + dateFormater.format(new Date()) + "</beginDate></requestxml>";
		try {
			org.apache.axis.client.Service axisService = new org.apache.axis.client.Service();
			Call call = (Call) axisService.createCall();
			call.setTargetEndpointAddress(sdUrl);
			call.setTimeout(20000);
			call.setOperationName("getSDStoreSalesAndReceivedData");
			String s = (String) call.invoke(new String[] { data });
			Document doc = DocumentHelper.parseText(s);
			Element root = doc.getRootElement().element("statisticsList");
			if (root != null) {
				@SuppressWarnings("unchecked")
				List<Element> list = root.elements();
				for (Element e : list) {
					CustomerSd sd=new CustomerSd();
					double salesMoney = Double.valueOf(String.valueOf(e.element("salesMoney").getData() == null ? 0l : e.element("salesMoney").getData()));
					double receivedMoney = Double.valueOf(String.valueOf(e.element("receivedMoney").getData() == null ? 0l : e.element("receivedMoney").getData()));
					String month=String.valueOf(e.element("statisticDate").getData());
					if(!"月平均".equals(month)){
						sd.setSaleAmount(salesMoney);
						sd.setPaymentAmount(receivedMoney);
						sd.setMonth(month);
						sd.setCno(cno);
						sd.setCreateTime(requestDate);
						sd.setUpdateTime(requestDate);
						sdList.add(sd);
					}
				}
			} 
		} catch (Exception e) {
			logger.error("客户CNO：[{}],SD:[{}],调用webservice接口异常：[{}]", cno,customerSd,e);
		}
		return sdList;
	}
}
